#ifndef CQ_THREAD_H
#define CQ_THREAD_H

#include "CQ_defines.h"
#include "CQ_looper.h"

#include <thread>
#include <memory>
#include <atomic>

DEFINE_NAMESPACE_CQ_BEGIN

constexpr int THREAD_TICK = 30;
class CQThread
{
public:
	CQThread() : m_running(false)
	{

	}

	virtual ~CQThread()
	{
		if (m_running) {
			m_running = false;
		}
	}

	bool start(LOOPER_TYPE type = REPEAT)
	{
		if (!m_running) {
			m_running = true;
			m_threadHandler.reset(new std::thread(&CQThread::_run, this, type));
			m_id = m_threadHandler->get_id();
			m_threadHandler->detach();
		}
		return m_running;
	}

	bool stop()
	{
		return m_running = false;
	}


	const std::thread::id& getId() const
	{
		return m_id;
	}

	virtual bool threadRun()
	{
		CQLooper::currentLooper()->exec();
		return true;
	}

private:

	void _run(LOOPER_TYPE type)
	{
		while (m_running && threadRun()) {
			CQLooper::currentLooper()->exec_once(THREAD_TICK);
			if (type == SINGLE) return;
		}
	}

	std::shared_ptr<std::thread> m_threadHandler;
	std::atomic_bool m_running;
	std::thread::id m_id;
};

DEFINE_NAMESPACE_CQ_END

#endif // CQ_THREAD_H
